package com.fablesoft.projectdatacollect.album;

import java.util.ArrayList;

import uk.co.senab.photoview.HackyViewPager;
import uk.co.senab.photoview.PhotoView;

import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 这个是用于进行图片浏览时的界面
 *
 * @author king
 * @QQ:595163260
 * @version 2014年10月18日  下午11:47:53
 */
public class GalleryActivity extends Activity {
    // 返回按钮
    private LinearLayout back_bt;
	// 发送按钮
	private TextView send_bt;
	//删除按钮
	private ImageView del_bt;
	//当前的位置
	private int location = 0;
	
	private ArrayList<View> listViews = null;
	private HackyViewPager pager;
	private MyPageAdapter adapter;
//	public List<Bitmap> bmp = new ArrayList<Bitmap>();
//	public List<String> drr = new ArrayList<String>();
//	public List<String> del = new ArrayList<String>();
	private String finishStr;
//	private LruCache<String, Bitmap> mMemoryCache;
	private String takePhotoUrl;
	RelativeLayout photo_relativeLayout;
	private int imageCount = 0;
	private int imageMaxCount = 0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		setContentView(R.layout.plugin_camera_gallery);// 切屏到主界面
		back_bt = (LinearLayout) findViewById(R.id.gallery_back);
		send_bt = (TextView) findViewById(R.id.send_button);
		del_bt = (ImageView)findViewById(R.id.gallery_del);
		back_bt.setOnClickListener(new BackListener());
		send_bt.setOnClickListener(new GallerySendListener());
		del_bt.setOnClickListener(new DelListener());
		finishStr = getString(R.string.finish);
		// 为发送按钮设置文字
		pager = (HackyViewPager) findViewById(R.id.gallery01);
		pager.setOnPageChangeListener(pageChangeListener);
		takePhotoUrl = getIntent().getStringExtra("takePhoto");
		if(TextUtils.isEmpty(takePhotoUrl)){
			for (int i = 0; i < ShowAllPhotoActivity.tempSelectBitmap.size(); i++) {
				initListViews();
			}
			imageCount = ShowAllPhotoActivity.tempSelectBitmap.size();
			imageMaxCount = ShowAllPhotoActivity.maxCount;
			del_bt.setVisibility(View.VISIBLE);
		}else{
			initListViews();
			imageCount = 1;
			imageMaxCount = 1;
			del_bt.setVisibility(View.GONE);
		}
		adapter = new MyPageAdapter(listViews);
		pager.setAdapter(adapter);
		pager.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.ui_5_dip));
		pager.setCurrentItem(0);
		isShowOkBt();
//		//获取应用程序的最大内存
//        final int maxMemory = (int) (Runtime.getRuntime().maxMemory());
//
//        //用最大内存的1/4来存储图片
//        final int cacheSize = maxMemory / 3;
//        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
//            
//            //获取每张图片的大小
//            @Override
//            protected int sizeOf(String key, Bitmap bitmap) {
//                return bitmap.getRowBytes() * bitmap.getHeight();
//            }
//        };
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		int h = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
		RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, h);
		rl.setMargins(0, result, 0, 0);
		View view = findViewById(R.id.headview);
		view.setLayoutParams(rl);
		view.setVisibility(View.VISIBLE);
	}
	
	private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {
			location = arg0;
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	};
	
	private void initListViews() {
		if (listViews == null)
			listViews = new ArrayList<View>();
		PhotoView img = new PhotoView(this);
		img.setBackgroundColor(0xff000000);
		img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		listViews.add(img);
	}
	
//	ImageCallback callback = new ImageCallback() {
//		@Override
//		public void imageLoad(ImageView imageView, Bitmap bitmap,
//				Object... params) {
//			if (imageView != null && bitmap != null) {
//				String url = (String) params[0];
//				Boolean isThumb = (Boolean) params[1];
//				Log.i("luzx", "isThumb:" + isThumb);
//				if (url != null && url.equals((String) imageView.getTag())) {
//					((ImageView) imageView).setImageBitmap(bitmap);
//					if(!isThumb){
//						Log.i("luzx", "put bitmap url:" + url + ";bitmap:" + bitmap);
//						mMemoryCache.put(url, bitmap);
//					}
//				} else {
//					Log.e("luzx", "callback, bmp not match");
//				}
//			} else {
//				Log.e("luzx", "callback, bmp null");
//			}
//		}
//	};
	
	// 返回按钮添加的监听器
	private class BackListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			finish();
		}
	}
	
	// 删除按钮添加的监听器
	private class DelListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			imageCount -= 1;
			if (listViews.size() == 1) {
				ShowAllPhotoActivity.tempSelectBitmap.clear();
				send_bt.setText(finishStr + "(" + imageCount + "/"+ imageMaxCount +")");
				finish();
			} else {
				ShowAllPhotoActivity.tempSelectBitmap.remove(location);
				pager.removeAllViews();
				listViews.remove(location);
				adapter.setListViews(listViews);
				send_bt.setText(finishStr + "(" + imageCount + "/"+ imageMaxCount +")");
				adapter.notifyDataSetChanged();
			}
			Intent intent = new Intent("data.broadcast.action");  
            sendBroadcast(intent);
		}
	}

	// 完成按钮的监听
	private class GallerySendListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if(ShowAllPhotoActivity.activity != null){
				if(!TextUtils.isEmpty(takePhotoUrl)){
					ShowAllPhotoActivity.tempSelectBitmap.clear();
					ImageItem item = new ImageItem();
					item.setImagePath(takePhotoUrl);
					ShowAllPhotoActivity.tempSelectBitmap.add(item);
				}
				ShowAllPhotoActivity.activity.setResult(RESULT_OK);
				ShowAllPhotoActivity.activity.finish();
				ShowAllPhotoActivity.activity = null;
			}
			finish();
		}
	}

	public void isShowOkBt() {
		if (imageCount > 0) {
			send_bt.setText(finishStr + "(" + imageCount + "/"+ imageMaxCount + ")");
			send_bt.setClickable(true);
			send_bt.setTextColor(0xffffffff);
		} else {
			send_bt.setClickable(false);
			send_bt.setTextColor(0xff6a6c6e);
		}
	}

	/**
	 * 监听返回按钮
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return true;
	}
	
	
	class MyPageAdapter extends PagerAdapter {
		DisplayImageOptions	mOptions = new DisplayImageOptions.Builder()
			.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
//			.showImageOnLoading(R.drawable.plugin_camera_no_pictures)
			.resetViewBeforeLoading(true).cacheOnDisc(false)
			.bitmapConfig(Bitmap.Config.RGB_565)
			.considerExifParams(true).build();
		private ArrayList<View> listViews;

		private int size;
		public MyPageAdapter(ArrayList<View> listViews) {
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		public void setListViews(ArrayList<View> listViews) {
			this.listViews = listViews;
			size = listViews == null ? 0 : listViews.size();
		}

		@Override
		public int getCount() {
			return size;
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((HackyViewPager) arg0).removeView(listViews.get(arg1 % size));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			ImageView imageView = (ImageView) listViews.get(arg1 % size);
			try {
				((HackyViewPager) arg0).addView(imageView, 0);

			} catch (Exception e) {
				Log4jUtil.e(e.toString());
			}
			String imagePath = "";
			if(TextUtils.isEmpty(takePhotoUrl)){
				imagePath = ShowAllPhotoActivity.tempSelectBitmap.get(arg1 % size).getImagePath();
			}else{
				imagePath = takePhotoUrl;
			}
			imageView.setTag(imagePath);
//			Bitmap bitmap = mMemoryCache.get(imagePath);
//			Log.i("luzx", "get bitmap url:" + imagePath + ";bitmap:" + bitmap);
//			if(bitmap != null){
//				Log.i("luzx", "get from mMemoryCache");
//				imageView.setImageBitmap(bitmap);
//			}else{
//				BitmapCache.getInstance().displayBmp(imageView, imagePath, 0, true, callback);
//				BitmapCache.getInstance().displayBmp(imageView, imagePath, 0, false, callback);
//			}
			ImageLoader.getInstance().displayImage("file://" + imagePath, imageView, mOptions);
			return listViews.get(arg1 % size);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
//		super.onRestoreInstanceState(savedInstanceState);
		finish();
	}
}
